set -e
if [ ! -d ./openssl ]; then
    rm -rf ./openssl
    git clone https://gitee.com/mirrors/openssl.git
    pushd openssl
        git checkout openssl-3.0.7
        ./Configure
        make -j256
    popd
fi
export LD_LIBRARY_PATH=$(readlink -f $(pwd)/openssl)
export openssl=./openssl/apps/openssl

function FileHexDump() {
    echo "begin dump file $1"
    xxd -p "$1" | tr -d '\n' | sed -zE 's#(.{32})#\1\n#g' | sed -E 's#(..)#0x\1, #g' | sed 's# $##'
    echo # echo new line, tr delete all \n in last command
}

function TrimOpensslText() {
    # https://unix.stackexchange.com/questions/202219/how-to-use-w-in-regular-expression-in-sed
    # sed 不支持直接在 [] 中使用 \w 所以这里用了 perl
    perl -pe 's#:##g;s#^(\w+[\w -]*)$#\1\n#' -i "$1"
    sed -zE 's#\n {4}##g' -i "$1"
}

# GetNthLine filename linenumber
function GetNthLine() {
    # https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file
    sed "$2 q;d" "$1"
}

# 注意，不要直接使用PEM格式的密钥base64解码后作为DER格式密钥使用，两者不太一致。
# base64解码方式： openssl base64 -d -in pubkey.pem -out pubkey.der
# 转成der格式方式： openssl rsa -pubin -in pubkey.pem -outform der -out pubkey.der
# https://stackoverflow.com/questions/52367234/generate-der-format-public-key-from-pem-format-certificate-and-pem-format-public
# If you were worried that the PEM contents were legal BER but not legal DER (for example,
# that it used indefinite-length constructed values), you could ask OpenSSL to read and write it.
